package tictactoe.multiplayer.server;

import tictactoe.Player;
import tictactoe.exceptions.network.NetworkException;
import tictactoe.exceptions.network.PlayerAlreadyInException;
import tictactoe.exceptions.network.PlayerNotInException;
import tictactoe.util.Constants;
import java.util.Collections;
import java.util.Hashtable;
import java.util.Set;

public class PlayerPoll {
    private Hashtable<Player, ClientHandler> players;

    public PlayerPoll() {
        players = new Hashtable<Player, ClientHandler>();
    }

    public synchronized void addPlayer(Player p, ClientHandler handler) throws NetworkException {
        if (players.contains(p)) {
            throw new PlayerAlreadyInException(p.getName() + "already logged");
        }
        players.put(p, handler);
    }

    public synchronized void removePlayer(Player p) throws NetworkException {
        if (!players.containsKey(p)) {
            throw new PlayerNotInException(p.getName() + " not in list");
        }
        players.remove(p);
    }

    public synchronized Set<Player> getPlayers() {
        return Collections.unmodifiableSet(players.keySet());
    }

    public synchronized ClientHandler getHandler(Player p) throws NetworkException {
        if (!players.containsKey(p)) {
            throw new PlayerNotInException(p.getName() + " not in list");
        } else {
            return players.get(p);
        }
    }

    public String getPlayersString() {
        Set<Player> set = getPlayers();
        StringBuilder sb = new StringBuilder();
        for (Player p: set) {
            if (sb.length() > 0) {
                sb.append(Constants.PLAYER_SEPARATOR);
            }
            sb.append(p.getName());
        }
        
        return sb.toString();
    }
}
